﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestConsoleApp
{
    public class TestTask
    {
        public static void Test()
        {

            //Console.WriteLine("Task Start !");
            ////DotaskWithThread();
            //DOTaskWithAsync();
            //Console.WriteLine("Task End !");
            //Console.ReadLine();

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Token.ThrowIfCancellationRequested();

            cancellationTokenSource.Cancel();



            Console.WriteLine("111 balabala. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
            var task = AsyncMethod();
            //Console.WriteLine(task.Result);
            Console.WriteLine("222 balabala. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);


            Task.Run(() =>
            {
                Thread.CurrentThread.Priority = ThreadPriority.Lowest;
            });

            ThreadPool.QueueUserWorkItem((arg) => { });
        }


        private static async Task<string> AsyncMethod()
        {
            var ResultFromTimeConsumingMethod = TimeConsumingMethod();
            string Result = await ResultFromTimeConsumingMethod + " + AsyncMethod. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine(Result);
            //返回值是Task的函数可以不用return
            Console.WriteLine("qx My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
            return Result;
        }

        //这个函数就是一个耗时函数，可能是IO操作，也可能是cpu密集型工作。
        private static Task<string> TimeConsumingMethod()
        {

            var task = Task.Run(() =>
            {
                Console.WriteLine("Helo I am TimeConsumingMethod. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                Console.WriteLine("Helo I am TimeConsumingMethod after Sleep(5000). My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
                return "Hello I am TimeConsumingMethod";
            });

            return task;
        }

        //public static async void DOTaskWithAsync()
        //{

        //    Console.WriteLine("Await Taskfunction Start");
        //    await Task.Run(() =>
        //    {
        //        Dotaskfunction();
        //    });


        //}

        //public static void Dotaskfunction()
        //{
        //    for (int i = 0; i <= 5; i++)
        //    {

        //        Console.WriteLine("task {0}  has been done!", i);
        //    }

        //}

    }
}
